import Router from 'koa-router'
import { pool } from '../../config/database'
import { authMiddleware } from '../../middleware/auth'
import { RowDataPacket } from 'mysql2'
import { ApiResponse } from '../../types'
import path from 'path'
import multer from '@koa/multer'

const router = new Router({ prefix: '/api/upload' })

// 测试路由
router.get('/test', (ctx) => {
  ctx.body = {
    success: true,
    message: '上传模块工作正常'
  }
})

// 配置multer
const upload = multer({
  storage: multer.memoryStorage(),

  limits: {
    fileSize: 2 * 1024 * 1024, // 2MB
    files: 1
  },

  fileFilter: (req: any, file: any, cb: any) => {
    const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp']
    if (allowedTypes.includes(file.mimetype)) {
      cb(null, true)
    } else {
      cb(new Error('只支持 JPEG、PNG、GIF、WebP 格式的图片文件'), false)
    }
  }
})

// 配置商品图片上传的multer (支持多文件)
const productImageUpload = multer({
  storage: multer.memoryStorage(),
  limits: {
    fileSize: 2 * 1024 * 1024, // 2MB per file
    files: 4 // 最多4个文件
  },
  fileFilter: (req: any, file: any, cb: any) => {
    const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp']
    if (allowedTypes.includes(file.mimetype)) {
      cb(null, true)
    } else {
      cb(new Error('只支持 JPEG、PNG、GIF、WebP 格式的图片文件'), false)
    }
  }
})

// 商品图片上传路由
router.post('/product-images', authMiddleware as any, async (ctx, next) => {
  await productImageUpload.array('images', 4)(ctx as any, next)
}, async (ctx) => {
  try {
    // 从multer处理的字段中获取productId - 尝试多种可能的位置
    const body = (ctx as any).request.body || {}
    const productIdStr = body.productId || (ctx as any).body?.productId
    const productId = productIdStr ? parseInt(productIdStr) : null
    const files = (ctx as any).files

    console.log('商品图片上传请求详情:', {
      productIdStr,
      productId,
      filesCount: files?.length || 0,
      requestBody: body,
      ctxBody: (ctx as any).body,
      allKeys: Object.keys(body)
    })

    // 验证产品ID和文件
    if (!productId || isNaN(productId) || !files || files.length === 0) {
      ctx.status = 400
      ctx.body = {
        success: false,
        message: `参数错误 - productId: ${productId} (原始值: ${productIdStr}), files: ${files?.length || 0}`,
        debug: {
          body,
          hasFiles: !!files,
          filesLength: files?.length || 0
        }
      }
      return
    }

    // 上传到OSS并获取URL数组
    const { ossService } = await import('../../config/oss')
    const uploadedImages: string[] = []

    for (let i = 0; i < files.length; i++) {
      const file = files[i]
      const fileExtension = path.extname(file.originalname).slice(1) || 'jpg'
      const fileName = `products/${productId}/${Date.now()}_${i}.${fileExtension}`

      const uploadResult = await ossService.uploadFile(fileName, file.buffer, {
        headers: { 'Content-Type': file.mimetype }
      })

      uploadedImages.push(`https://xlcig.oss-cn-beijing.aliyuncs.com/${fileName}`)
    }

    // 获取现有图片并合并
    const [existingProduct] = await pool.execute(
      'SELECT images FROM products WHERE id = ?', [productId]
    ) as [RowDataPacket[], any]

    let allImages: string[] = []
    if (existingProduct[0]?.images) {
      try {
        const existing = JSON.parse(existingProduct[0].images)
        allImages = Array.isArray(existing) ? existing : []
      } catch (e) { allImages = [] }
    }

    allImages.push(...uploadedImages)
    if (allImages.length > 4) {
      allImages = allImages.slice(-4) // 保留最新4张
    }

    // 更新数据库
    await pool.execute(
      'UPDATE products SET images = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
      [JSON.stringify(allImages), productId]
    )

    ctx.body = {
      success: true,
      data: { images: allImages },
      message: `成功上传${uploadedImages.length}张图片`
    }

  } catch (error: any) {
    ctx.status = 500
    ctx.body = { success: false, message: '上传失败: ' + error.message }
  }
})

// 删除商品图片路由
router.delete('/product-images/:productId/:imageIndex', authMiddleware as any, async (ctx) => {
  try {
    const productId = parseInt(ctx.params.productId)
    const imageIndex = parseInt(ctx.params.imageIndex)

    if (!productId || imageIndex < 0 || imageIndex > 4) {
      ctx.status = 400
      ctx.body = {
        success: false,
        message: '参数错误，图片索引必须在0-4之间'
      } as ApiResponse
      return
    }

    // 获取现有商品图片
    const [existingProduct] = await pool.execute(
      'SELECT images FROM products WHERE id = ?',
      [productId]
    ) as [RowDataPacket[], any]

    if (existingProduct.length === 0) {
      ctx.status = 404
      ctx.body = {
        success: false,
        message: '产品不存在'
      } as ApiResponse
      return
    }

    // 解析现有images数组
    let imagesArray: string[] = ['', '', '', '', '']
    if (existingProduct[0].images) {
      try {
        const existing = typeof existingProduct[0].images === 'string'
          ? JSON.parse(existingProduct[0].images)
          : existingProduct[0].images
        if (Array.isArray(existing)) {
          for (let i = 0; i < Math.min(existing.length, 5); i++) {
            imagesArray[i] = existing[i] || ''
          }
        }
      } catch (e) {
        ctx.status = 400
        ctx.body = {
          success: false,
          message: '图片数据格式错误'
        } as ApiResponse
        return
      }
    }

    if (imagesArray[imageIndex] === '') {
      ctx.status = 400
      ctx.body = {
        success: false,
        message: '该位置暂无图片'
      } as ApiResponse
      return
    }

    // 删除指定位置的图片（设为空字符串）
    imagesArray[imageIndex] = ''

    // 更新数据库
    await pool.execute(
      'UPDATE products SET images = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
      [JSON.stringify(imagesArray), productId]
    )

    ctx.body = {
      success: true,
      data: {
        images: imagesArray
      },
      message: `${imageIndex === 4 ? '详情图' : '商品图片'}删除成功`
    } as ApiResponse

  } catch (error: any) {
    console.error('删除商品图片失败:', error)
    ctx.status = 500
    ctx.body = {
      success: false,
      message: '删除图片失败'
    } as ApiResponse
  }
})

// 图片上传路由
router.post('/avatar', authMiddleware as any, async (ctx, next) => {
  // 使用multer中间件
  await upload.single('avatar')(ctx as any, next)
}, async (ctx) => {
  try {
    const userId = ctx.state.user.id as number
    const file = (ctx as any).file
    if (!file) {
      console.log('文件上传失败：未收到文件')
      ctx.status = 400
      ctx.body = {
        success: false,
        message: '请选择要上传的头像文件'
      } as ApiResponse
      return
    }

    console.log('上传的文件信息:', {
      originalname: file.originalname,
      mimetype: file.mimetype,
      size: file.size
    })

    // 验证文件类型
    const allowedMimeTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp']
    if (!allowedMimeTypes.includes(file.mimetype)) {
      ctx.status = 400
      ctx.body = {
        success: false,
        message: '只支持 JPEG、PNG、GIF、WebP 格式的图片文件'
      } as ApiResponse
      return
    }

    // 验证文件大小
    if (file.size > 2 * 1024 * 1024) {
      ctx.status = 400
      ctx.body = {
        success: false,
        message: '文件大小不能超过2MB'
      } as ApiResponse
      return
    }

    try {
      // 动态导入OSS配置
      const { ossService, validateOSSConfig } = await import('../../config/oss')

      // 验证OSS配置
      if (!validateOSSConfig()) {
        ctx.status = 500
        ctx.body = {
          success: false,
          message: '文件上传服务未配置'
        } as ApiResponse
        return
      }

      // 生成文件名
      const fileExtension = path.extname(file.originalname).slice(1) || 'jpg'
      const fileName = ossService.generateAvatarFileName(userId, fileExtension)

      console.log('准备上传到OSS:', fileName)

      // 上传到OSS
      const uploadResult = await ossService.uploadFile(fileName, file.buffer, {
        headers: {
          'Content-Type': file.mimetype
        }
      })

      console.log('OSS上传成功:', uploadResult.name)

      // 获取文件访问URL
      const avatarUrl = `https://xlcig.oss-cn-beijing.aliyuncs.com/${fileName}`

      // 更新数据库中的用户头像
      await pool.execute(
        'UPDATE users SET avatar = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
        [avatarUrl, userId]
      )

      // 获取更新后的用户信息
      const [users] = await pool.execute(
        'SELECT id, email, username, nickname, phone, avatar, role, created_at, updated_at FROM users WHERE id = ?',
        [userId]
      ) as [RowDataPacket[], any]
      console.log('头像上传完成:', avatarUrl)
      ctx.body = {
        success: true,
        data: {
          avatar: avatarUrl,
          user: users[0]
        },
        message: '头像上传成功'
      } as ApiResponse

    } catch (ossError: any) {
      console.error('OSS上传失败:', ossError)

      ctx.status = 500
      ctx.body = {
        success: false,
        message: '文件上传失败，请重试: ' + ossError.message
      } as ApiResponse
    }

  } catch (error: any) {
    console.error('头像上传失败:', error)

    // 处理multer错误
    if (error.code === 'LIMIT_FILE_SIZE') {
      ctx.status = 400
      ctx.body = {
        success: false,
        message: '文件大小不能超过2MB'
      } as ApiResponse
      return
    }

    ctx.status = 500
    ctx.body = {
      success: false,
      message: error.message || '头像上传失败'
    } as ApiResponse
  }
})

export default router 